package git.soulbgm.sync.interceptor;

import git.soulbgm.sync.task.SyncDataBaseTask;
import git.soulbgm.sync.web.DBSyncController;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;

/**
 * sql拦截器
 *
 * @author SoulBGM
 * @date 2022/04/22 14:50
 */
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class SqlInterceptor implements Interceptor {

    private final static Logger log = LoggerFactory.getLogger(SqlInterceptor.class);

    private final static String SQL_COMMAND_TYPE_INSERT = "INSERT";
    private final static String SQL_COMMAND_TYPE_UPDATE = "UPDATE";
    private final static String SQL_COMMAND_TYPE_DELETE = "DELETE";

    private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private final SyncDataBaseTask task;

    public SqlInterceptor(SyncDataBaseTask task) {
        this.task = task;
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        boolean executeRealMethod = isSyncDataBaseControllerClassExecute(Thread.currentThread().getStackTrace());
        if (executeRealMethod) {
            return invocation.proceed();
        }
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object parameterObject = null;
        if (invocation.getArgs().length > 1) {
            parameterObject = invocation.getArgs()[1];
        }
        //id为执行的mapper方法的全路径名，如com.uv.dao.UserMapper.insertUser
        // String id = mappedStatement.getId();
        // log.info("拦截到当前请求方法的全路径名为--->:  " + id);
        //sql语句类型 select、delete、insert、update
        String sqlCommandType = mappedStatement.getSqlCommandType().toString();
        if (SQL_COMMAND_TYPE_INSERT.equals(sqlCommandType) || SQL_COMMAND_TYPE_UPDATE.equals(sqlCommandType) || SQL_COMMAND_TYPE_DELETE.equals(sqlCommandType)) {
            //获取参数
            BoundSql boundSql = mappedStatement.getBoundSql(parameterObject);
            //获取拼接后的sql语句
            String sql = getSql(boundSql, parameterObject, mappedStatement.getConfiguration());
            sql = sql.replace("\n", "");
            task.sync(sql);
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
//        this.setProperties(properties);
    }

    /**
     * 判断是否是 HandleCacheData 类执行的
     *
     * @param stackTrace 堆栈跟踪
     * @return boolean
     */
    private boolean isSyncDataBaseControllerClassExecute(StackTraceElement[] stackTrace) {
        boolean flag = false;
        for (StackTraceElement element : stackTrace) {
            if (element.getClassName().equals(DBSyncController.class.getName())) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    /**
     * 获得sql
     *
     * @param boundSql        绑定sql
     * @param parameterObject 参数对象
     * @param configuration   配置
     * @return {@link String}
     */
    private String getSql(BoundSql boundSql, Object parameterObject, Configuration configuration) {
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
        if (parameterMappings != null) {
            for (int i = 0; i < parameterMappings.size(); i++) {
                ParameterMapping parameterMapping = parameterMappings.get(i);
                if (parameterMapping.getMode() != ParameterMode.OUT) {
                    Object value;
                    String propertyName = parameterMapping.getProperty();
                    if (boundSql.hasAdditionalParameter(propertyName)) {
                        value = boundSql.getAdditionalParameter(propertyName);
                    } else if (parameterObject == null) {
                        value = null;
                    } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                        value = parameterObject;
                    } else {
                        MetaObject metaObject = configuration.newMetaObject(parameterObject);
                        value = metaObject.getValue(propertyName);
                    }
                    sql = replacePlaceholder(sql, value);
                }
            }
        }
        return sql;
    }

    /**
     * 替换占位符
     *
     * @param sql           sql
     * @param propertyValue 属性值
     * @return {@link String}
     */
    private String replacePlaceholder(String sql, Object propertyValue) {
        String result;
        if (propertyValue != null) {
            if (propertyValue instanceof String) {
                result = "'" + propertyValue + "'";
            } else if (propertyValue instanceof Date) {
                result = "'" + DATE_FORMAT.format(propertyValue) + "'";
            } else {
                result = propertyValue.toString();
            }
        } else {
            result = "null";
        }
        return sql.replaceFirst("\\?", Matcher.quoteReplacement(result));
    }
}
